package ch.zbw.swt.sysventory.network.scan;

import ch.zbw.swt.sysventory.hibernate.entity.Computer;
import ch.zbw.swt.sysventory.hibernate.entity.OperatingSystem;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanOperatingSystem {

	private OperatingSystem oSystem;
	private Computer computer;

	// Constructor
	public ScanOperatingSystem(Computer computer) {
		this.computer = computer;
	}

	/*
	 * Read entrys from OS
	 */
	public OperatingSystem getOperatingSystem(String host) {

		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_OperatingSystem";
		try {
			// Load Library
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);
			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// The Rusult is a Collection
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a
				// java
				// form.
				String nameOperatingSystem = Dispatch.call(item, "Caption")
						.toString();
				String buildOperatingSystem = Dispatch.call(item, "Version")
						.toString();
				String architectureOperatingSystem = "NA";
				try {
					architectureOperatingSystem = Dispatch.call(item,
							"OSArchitecture").toString();
				} catch (Exception e) {
				}

				oSystem = new OperatingSystem(nameOperatingSystem,
						buildOperatingSystem, architectureOperatingSystem,
						computer);
			}
		} catch (Exception e) {

		}

		return oSystem;
	}
}
